<template>
	<view class="content">
		<z-paging ref="paging" height="100%" v-model="OLdatas" @query="queryList">
			<view class="footer-box" v-if="OLdatas && OLdatas.length > 0">
				<view class="footer-item" v-for="(item, index) in OLdatas" :key="index" @click="viewMessage(item)">
					<view class="footer-left">
						<image class="footer-image" :src="imgcoin" mode="aspectFill" />
					</view>
					<view
						style="display:flex; justify-content: space-between;width: 90%; padding-bottom:20rpx; margin-top: 10rpx;">
						<view class="footer-text-container">
							<view class="footer-title">{{item.neiRong}}</view>
							<view class="footer-date" :class="{'unread': !item.isRead}">{{item.note}}</view>
						</view>
						<view class="message-time">{{ formatTime(item.createTime || new Date()) }}</view>
					</view>
				</view>
			</view>
			<view class="empty-state" v-else>
				<image src="/static/image/meiyoushuju.png" mode="aspectFit"></image>
				<text>暂无消息</text>
			</view>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick,
		watch
	} from 'vue';

	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		getMesslist
	} from "@/api/xiaoquan.js";
	// import useStorage from '@/utils/storage.js';
	// 修改后的时间格式化函数
	const formatTime = (time) => {
		let inputTime;
		if (typeof time === 'number') {
			inputTime = new Date(time);
		} else if (typeof time === 'string') {
			inputTime = new Date(time);
			if (isNaN(inputTime.getTime())) {
				inputTime = new Date(Date.parse(time.replace(/-/g, '/')));
			}
		} else if (time instanceof Date) {
			inputTime = time;
		} else {
			inputTime = new Date();
		}

		const now = new Date();
		const timeDiff = now - inputTime;
		const minutesDiff = Math.floor(timeDiff / (1000 * 60));
		const hoursDiff = Math.floor(timeDiff / (1000 * 60 * 60));
		const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

		if (minutesDiff < 60 && minutesDiff >= 0) {
			return `${minutesDiff}分钟前`;
		} else if (hoursDiff < 24 && hoursDiff > 0) {
			return `${hoursDiff}小时前`;
		} else {
			const year = inputTime.getFullYear();
			const month = String(inputTime.getMonth() + 1).padStart(2, '0');
			const day = String(inputTime.getDate()).padStart(2, '0');
			const hour = String(inputTime.getHours()).padStart(2, '0');
			const minute = String(inputTime.getMinutes()).padStart(2, '0');
			const second = String(inputTime.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		}
	};
	const OLdatas = ref([]);
	const types = ref(null);
	const currentPage = ref(1);
	const pageSize = ref(10);
	const totalPages = ref(1);
	const imgcoin = ref('/static/image/xitong.png');

	// 消息类型映射
	const typeMap = {
		1: {
			img: "/static/image/kefu.png",
			title: "我的客服"
		},
		2: {
			img: "/static/image/xitong.png",
			title: "系统通知"
		},
		3: {
			img: "/static/image/huodong.png",
			title: "活动通知"
		}
	};

	// 校圈列表查询
	const queryList = (pageNo, pageSize) => {
		currentPage.value = pageNo;
		OLdata();
	};

	// 获取消息数据
	const OLdata = async () => {
		// const token = useStorage.get('token');
		// if (!token) {
		// 	uni.showToast({
		// 		title: '请先登录',
		// 		icon: 'none'
		// 	});
		// 	return;
		// }

		try {
			const res = await getMesslist(
				types.value
			);

			console.log('消息详情数据:', res);

			if (res.code === 200 && res.data) {
				OLdatas.value = res.data || [];
				// totalPages.value = Math.ceil(res.data.total / pageSize.value);

				// 标记消息为已读
				markAsRead();
			} else {
				OLdatas.value = [];
				uni.showToast({
					title: res.message || '获取消息失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取消息详情失败:', error);
			OLdatas.value = [];
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		}
	};

	// 标记消息为已读
	const markAsRead = () => {
		// 这里应该调用后端接口标记消息为已读
		// 假设接口为 markMessageAsRead(id)
		/*
		if (OLdatas.value.length > 0) {
		  const unreadIds = OLdatas.value
		    .filter(item => item.isRead === 0)
		    .map(item => item.id);
		  
		  if (unreadIds.length > 0) {
		    markMessageAsRead(unreadIds).then(() => {
		      console.log('消息已标记为已读');
		    });
		  }
		}
		*/
	};

	// 查看消息详情
	const viewMessage = (item) => {
		// 如果id不为空，跳转到帖子详情
		if (item) {
			// console.log(item, "-----------")
			// 把点击的帖子基本信息村起来。
			let item1 = {
				id: item.tieZiId
			}
			uni.setStorageSync("itemDetail", item1)
			console.log("111111111111111111=============", item)
			// console.log(uni.getStorageSync("itemDetail"))
			uni.navigateTo({
				url: `/package/pages/postDetail/postDetail?id=${item.tieZiId}`
			});
		}

	};

	// 页面加载时获取参数和数据
	onLoad((e) => {
		if (e.typeid) {
			types.value = parseInt(e.typeid);
			const typeInfo = typeMap[types.value];
			if (typeInfo) {
				imgcoin.value = typeInfo.img;
				uni.setNavigationBarTitle({
					title: typeInfo.title
				});
			}
		}

		OLdata();
	});

	// 页面显示时刷新数据
	onShow(() => {
		OLdata();
	});
</script>

<style scoped>
	.content {
		padding: 0 30rpx;
		border-top: 1rpx solid #dddddd;
	}

	.footer-box {
		background-color: white;
		border-radius: 10rpx;
		padding: 0 20rpx;
		height: 100vh;
	}

	.footer-item {
		padding-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 30rpx;
		position: relative;
		border-bottom: 1rpx solid #dddddd;
		padding-bottom: 30rpx;
	}

	.footer-left {
		display: flex;
		align-items: center;
		padding-bottom: 20rpx;
	}

	.footer-image {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
	}

	.footer-text-container {
		margin-left: 20rpx;
		position: relative;
		flex: 1;
		margin-right: 20rpx;
	}

	.footer-title {
		font-size: 34rpx;
		color: #000;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.footer-date {
		color: #999999;
		font-size: 28rpx;
		margin-top: 26rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.unread {
		color: #ff4d4f;
		font-weight: bold;
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
		width: 120rpx;
		text-align: right;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}

	.empty-state image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-state text {
		color: #999;
		font-size: 28rpx;
	}
</style>